import 'package:event_bus/event_bus.dart';

class EventBusUtils {
  static const String globalEventBus = "globalEventBus";

  static EventBus get(String name) {
    return _EventFactory(name);
  }

  static EventBus get global {
    return _EventFactory(globalEventBus);
  }
}

class _EventFactory extends EventBus {
  static Map<String, _EventFactory>? _instanceList;

  String name;

  _EventFactory._(this.name);

  factory _EventFactory(String name) => _getInstance(name);

  static _EventFactory _getInstance(String name) {
    if (_instanceList == null) {
      _instanceList = {};
      var instance = _EventFactory._(name);
      _instanceList![name] = instance;
      return instance;
    }

    var instance = _instanceList![name];
    if (instance != null) {
      return instance;
    }

    instance = _EventFactory._(name);

    _instanceList![name] = instance;
    return instance;
  }

  @override
  void destroy() {
    if (_instanceList != null) {
      _instanceList!.remove(name);
    }

    super.destroy();
  }
}
